const {verifyToken}  = require('../utils/jwt.js');

function authenticateToken(req, res, next) {
    const authHeader = req.headers['authorization'];
    const token = authHeader && authHeader.split(' ')[1];
  
    if (token == null) return res.sendStatus(401);
  
    try {
      const user = verifyToken(token);
      req.user = user;
      next();
    } catch (error) {
      // 根据错误类型返回不同的HTTP状态码
      if (error.name === 'TokenExpiredError') {
        return res.status(401).send('Token expired');
      } else {
        return res.status(403).send('Token invalid');
      }
    }
  }
  module.exports = authenticateToken;